package com.shujia.spark.stream

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import scala.io.Source

object Demo8CarToKafka {
  def main(args: Array[String]): Unit = {
    //1、创建生产者

    val properties = new Properties()
    //1、kafka broker列表
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    //2、指定kv的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    val kafkaProducer = new KafkaProducer[String, String](properties)

    /**
      * 读取卡口过车的数据，将数据实时写入kafka中
      *
      */

    val cars: Iterator[String] = Source.fromFile("data/cars_sample.json").getLines()

    cars.foreach(car => {
      val record = new ProducerRecord[String, String]("cars", car)
      kafkaProducer.send(record)
      kafkaProducer.flush()
      println("写入成功")
      Thread.sleep(500)
    })

    kafkaProducer.close()


  }

}
